package com.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.health.constant.MessageConstant;
import com.health.dao.MenuDao;
import com.health.dao.PermissionDao;
import com.health.dao.RoleDao;
import com.health.dao.UserDao;
import com.health.entity.PageResult;
import com.health.entity.QueryPageBean;
import com.health.entity.Result;
import com.health.pojo.Menu;
import com.health.pojo.Permission;
import com.health.pojo.Role;
import com.health.pojo.User;
import com.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @Classname UserServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/17 8:23
 * @Author RainGrd
 */
@Service(interfaceClass = UserService.class)
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;

    @Override
    public User queryByUserName(String userName) {
        User user = userDao.selectUserByUserName(userName);
        if (user != null) {
            Integer userId = user.getId();
            Set<Role> roles = roleDao.findRoleByUserId(userId);
            log.info("查询出来的角色:{}", roles);
            if (roles != null && roles.size() > 0) {
                for (Role role : roles) {
                    Integer roleId = role.getId();
                    //权限关键字
                    Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                    if (permissions != null && permissions.size() > 0) {
                        role.setPermissions(permissions);
                    }
                    LinkedHashSet<Menu> menus = menuDao.selectMenuByRoleId(roleId);
                    log.info("menus:{}", menus);
                    //权限菜单
                    role.setMenus(menus);
                }
                user.setRoles(roles);
            }
        }
        return user;
    }

    @Override
    public PageResult queryUserPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //查询角色
        List<User> users = userDao.selectUserByCondition(queryPageBean.getQueryString());
        log.info("users:{}", users);
        //遍历角色
        for (User user : users) {
            log.info("user:{}", user);
            user.setRoles(roleDao.selectRolesByUserId(user.getId()));
        }
        return new PageResult(userDao.selectTotalByCondition(queryPageBean.getQueryString()), users);
    }

    @Override
    public Result saveUser(User user, Integer[] roleIds) {
        try {
            //进行SHA-256+随机盐+密钥加密
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String encode = bCryptPasswordEncoder.encode("123456");
            //封装密码
            user.setPassword(encode);

            Set<Role> roles = user.getRoles();
            for (Role role : roles) {
                String keyword = role.getKeyword();
                //判断是否是患者
                if (keyword.equals("ROLE_PATIENT")) {
                    //默认填充没有答题
                    user.setFlag(0);
                    //默认填充已启用
                    user.setStation("1");
                }
            }
            int i = userDao.insertUser(user);
            log.info("user:{}", user);
            //插入菜单与角色表
            setUserIdAndRoleIds(user.getId(), roleIds);
            return i > 0 ? Result.success(MessageConstant.ADD_CHECKITEM_SUCCESS) : Result.error(MessageConstant.ADD_CHECKITEM_FAIL);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error(MessageConstant.ADD_CHECKITEM_FAIL);
        }
    }

    @Override
    public Result editUser(User user, Integer[] roleIds) {
        try {
            //根据检查组id删除中间表数据（清理原有关联关系）
            userDao.deleteAssociation(user.getId());
            //重新补充中间表
            setUserIdAndRoleIds(user.getId(), roleIds);

            //正式编辑用户
            int i = userDao.updateUser(user);
            return i > 0 ? Result.success(MessageConstant.EDIT_CHECKGROUP_SUCCESS) : Result.error(MessageConstant.EDIT_CHECKGROUP_FAIL);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error();
        }
    }

    @Override
    public List<Integer> queryRoleIdsByUserId(Integer userId) {
        return userDao.selectRoleIdsByUserId(userId);
    }

    @Override
    public Result clearUser(Integer id) {
        //删除检查组
        try {
            //根据检查组id删除中间表数据（清理原有关联关系）
            userDao.deleteAssociation(id);
            //删除检查组
            int i = userDao.deleteUser(id);
            return i > 0 ? Result.success(MessageConstant.DELETE_CHECKGROUP_SUCCESS) : Result.error(MessageConstant.DELETE_CHECKGROUP_FAIL);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error();
        }
    }

    @Override
    public Result queryUserRoleAll() {
        return Result.success(userDao.selectUserRoleAll());
    }

    /**
     * 用于设置套餐与检查组的关系
     *
     * @param roleIds
     * @param userId
     */
    private void setUserIdAndRoleIds(Integer userId, Integer[] roleIds) {
        //判断检查项目Id数组是否为空
        if (roleIds != null && roleIds.length > 0) {
            //添加检查组和检查项
            for (Integer roleId : roleIds) {
                log.info("roleId:{}", roleId);
                userDao.insertUserAndRole(userId, roleId);
            }
        }
    }

}
